import cv2
import numpy as np
import pyautogui
from ultralytics import YOLO
import time
from 检测框模块 import get_window_screenshot


def movefbdiansha(hwnd, left, top, window_width, window_height, model, enemy_index,
           offset_x=0, offset_y=0, 置信度=0.5, click_type='left', mouse_shape_image=None,
           error_threshold=3):  # 新增误差参数，默认阈值3像素
    loop_count = 0
    while loop_count < 1:  # 可根据实际需求调整循环次数
        # 获取窗口截图
        screenshot = get_window_screenshot(hwnd)
        # 进行目标检测
        results = model(screenshot)

        dart_center_x, dart_center_y = None, None
        enemy_boxes = []

        for result in results:
            boxes = result.boxes.cpu().numpy()
            for box in boxes:
                class_id = int(box.cls[0])
                conf = box.conf[0]

                if class_id == 0:  # 检测准星（类别 0）
                    x1, y1, x2, y2 = box.xyxy[0].astype(int)
                    dart_center_x = int((x1 + x2) / 2) - 20  # 准星中心 x 坐标
                    dart_center_y = int((y1 + y2) / 2) - 20  # 准星中心 y 坐标

                if class_id == 1 and conf >= 置信度:
                    enemy_boxes.append(box.xyxy[0].astype(int))

        # 按 x 坐标排序敌人框，以确定从左到右的顺序
        enemy_boxes.sort(key=lambda box: box[0])

        # 检查指定序号的敌人是否存在
        if 0 < enemy_index <= len(enemy_boxes):
            target_box = enemy_boxes[enemy_index - 1]
            target_center_x = int((target_box[0] + target_box[2]) / 2) + offset_x + 1  # 目标中心 x 坐标
            target_center_y = int((target_box[1] + target_box[3]) / 2) + offset_y + 1  # 目标中心 y 坐标
            target_screen_x = left + target_center_x
            target_screen_y = top + target_center_y

            if dart_center_x is not None and dart_center_y is not None:
                # 首次移动到目标位置（应用距离缩放）
                current_pos = pyautogui.position()
                dx = (target_screen_x - current_pos[0]) * 0.85  # 实际移动距离为计算值的80%
                dy = (target_screen_y - current_pos[1]) * 0.85
                new_target_x = current_pos[0] + dx
                new_target_y = current_pos[1] + dy
                distance = np.sqrt(dx**2 + dy**2)
                duration = distance / 100 * 0.01
                pyautogui.moveTo(new_target_x, new_target_y, duration=duration)  # 平滑移动

                # 检测和计算准星与目标的距离，调整移动（应用距离缩放+误差阈值）
                while True:
                    screenshot = get_window_screenshot(hwnd)
                    results = model(screenshot)
                    dart_center_x, dart_center_y = None, None
                    for result in results:
                        boxes = result.boxes.cpu().numpy()
                        for box in boxes:
                            if int(box.cls[0]) == 0:
                                x1, y1, x2, y2 = box.xyxy[0].astype(int)
                                dart_center_x = int((x1 + x2) / 2) - 20
                                dart_center_y = int((y1 + y2) / 2) - 20
                                break

                    if dart_center_x is not None and dart_center_y is not None:
                        # 计算准星到目标的原始距离（用于误差判定）
                        dx_original = target_center_x - dart_center_x
                        dy_original = target_center_y - dart_center_y
                        # 实际移动距离为原始距离的80%
                        dx = dx_original * 0.80
                        dy = dy_original * 0.80

                        current_x, current_y = pyautogui.position()
                        new_x = current_x + dx  # 基于当前位置累加缩放后的距离
                        new_y = current_y + dy

                        # 限制鼠标在窗口附近移动（放宽 50 像素）
                        new_x = max(left - 50, min(new_x, left + window_width + 50))
                        new_y = max(top - 50, min(new_y, top + window_height + 50))

                        distance = np.sqrt(dx**2 + dy**2)
                        duration = distance / 100 * 0.051
                        # 常规平滑移动，持续时间根据距离计算
                        pyautogui.moveTo(new_x, new_y, duration=duration)

                        # 使用误差参数控制停止条件
                        if np.sqrt(dx_original ** 2 + dy_original ** 2) < error_threshold:
                            break

                pyautogui.click(button=click_type)
        else:
            print(f"指定序号 {enemy_index} 的敌人不存在。")

        loop_count += 1
        time.sleep(0.1)

    return False
